<template>
  <div class="flow-detail">
    <div class="app-container">
      <div class="designer-wrap">
        <div class="header">
          <el-menu
            :default-active="activeIndex"
            class="el-menu-demo"
            mode="horizontal"
            @select="handleSelect"
          >
            <el-menu-item v-for="item in menuItems" :key="item.index" :index="item.index">
              {{ item.label }}
            </el-menu-item>
          </el-menu>
          
          <div class="publish">
            <el-button @click="goback">
              <el-icon><ArrowLeft /></el-icon>
              返回
            </el-button>
            <el-button type="primary" @click="publish">
              <el-icon><Upload /></el-icon>
              发布
            </el-button>
          </div>
        </div>

        <div class="content">
          <component 
            :is="currentComponent"
            :navable="navable"
            :readable="readable"
            :form="formData"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useStore } from 'vuex'
import { ArrowLeft, Upload } from '@element-plus/icons-vue'
import { getStartNode } from '../utils/nodeUtil'
import { getFlowDataInfo, addFlowTemplate } from '../api/flow'
import formDesigner from '../components/FlowDesign/FlowForm/FormIndex.vue'
import BasicInfo from '../components/FlowDesign/BasicInfo/index.vue'
import FlowNode from '../components/FlowDesign/FlowNode/index.vue'
import FlowSetting from '../components/FlowDesign/FlowSetting/index.vue'

// 菜单配置
const menuItems = [
  { index: '1', label: '流程配置' },
  { index: '2', label: '流程表单' },
  { index: '3', label: '流程设计' },
  { index: '4', label: '流程设置' }
]

// 状态管理
const store = useStore()
const route = useRoute()
const router = useRouter()
const activeIndex = ref('1')

// Props定义
const props = defineProps({
  node: {
    type: Object,
    default: () => getStartNode()
  },
  navable: Boolean,
  readable: Boolean
})

// 计算属性
const nodeData = computed(() => store.state.process.node)
const formData = computed(() => store.state.form.config)
const baseSetting = computed(() => store.state.process.baseSetting)

// 当前显示的组件
const currentComponent = computed(() => {
  const components = {
    '1': BasicInfo,
    '2': formDesigner,
    '3': FlowNode,
    '4': FlowSetting
  }
  return components[activeIndex.value]
})

// 初始化数据
const initData = async () => {
  try {
    const id = route.query.id
    if (id) {
      const res = await getFlowDataInfo({ id })
      if (res.status === 0) {
        const data = {
          baseSetting: JSON.parse(res.data.baseSetting),
          node: JSON.parse(res.data.nodeData),
          formData: JSON.parse(res.data.formData)
        }
        store.dispatch("form/updateConfig", data.formData)
        store.dispatch("process/loadDesign", data)
      }
    } else {
      const data = {
        baseSetting: {},
        node: getStartNode(),
        formData: {
          config: {},
          list: []
        }
      }
      store.dispatch("process/loadDesign", data)
    }
  } catch (error) {
    console.error('初始化数据失败:', error)
  }
}

// 返回上一页
const goback = () => {
  router.back()
}

// 发布流程
const publish = async () => {
  try {
    const data = {
      name: baseSetting.value.flowName,
      remark: baseSetting.value.description,
      imgUrl: baseSetting.value.imageUrl,
      groupId: baseSetting.value.flowGroup,
      nodeData: JSON.stringify(nodeData.value),
      baseSetting: JSON.stringify(baseSetting.value),
      formData: JSON.stringify(formData.value)
    }
    
    const res = await addFlowTemplate(data)
    if (res.status === 0) {
      ElMessage.success('发布成功')
      //router.push('/flow/list')
    }
  } catch (error) {
    console.error('发布失败:', error)
    ElMessage.error('发布失败')
  }
}

// 切换菜单
const handleSelect = (key) => {
  activeIndex.value = key
}

// 监听节点数据变化
watch(nodeData, (newValue) => {
  console.log('节点数据更新:', newValue)
}, { immediate: true })

// 监听路由变化
watch(route, (to, from) => {
  console.log('路由变化:', { to, from })
})

// 初始化
initData()
</script>


<style lang="scss" scoped>
.flow-detail {
  min-height: 100vh;
  background-color: #f5f7fa;

  .app-container {
    padding: 20px;

    .designer-wrap {
      .header {
        min-width: 980px;
        position: relative;
        background-color: #fff;
        box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);

        .el-menu {
          top: 0;
          z-index: 999;
          display: flex;
          justify-content: center;
          width: 100%;
          border: none;
        }

        .publish {
          position: absolute;
          top: 15px;
          right: 20px;
          z-index: 1000;

          .el-button {
            border-radius: 15px;
            height: 32px;
            padding: 0 16px;
            margin-left: 8px;

            i {
              margin-right: 6px;
            }
          }
        }
      }

      .content {
        margin-top: 20px;
        animation: fadeIn 0.3s ease-out;
      }
    }
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(8px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>